package com.zhenyi.tuangou.admin.index;

import com.jfinal.aop.Clear;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zhenyi.common.model.TgType;

public class TypeController extends AdminController {

	@Override
	public void list() {
		Kv kv = Kv.by("shopId", getShopId());
		SqlPara sqlPara = Db.getSqlPara("FindAdminTypes", kv);
		Page<Record> pages = Db.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}
	
	public void info() {
		Long typeId = getParaToLong("id");
		TgType info = TgType.dao.findById(typeId);
		renderSuccess(info);
	}

	@Clear
	public void submit() {
		Long id = getParaToLong("id");
		String title = getPara("title");
		String subtitle = getPara("subtitle");
		String logo = getPara("logo");
		Long shopId = getShopId();
		
		boolean isNew = id == null;
		if (StrKit.isBlank(title)) {
			renderFailure();
			return;
		}
		TgType type = isNew ? new TgType() : TgType.dao.findById(id);
		if (!isNew && type == null) {
			renderFailure(404, "type not found");
			return;
		}
		type.setTitle(title);
		type.setSubtitle(subtitle);
		type.setLogo(logo);
		type.setShopId(shopId);
		boolean flag = isNew ? type.save() : type.update();
		if (flag) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}

	@Override
	public void delete() {
		Long typeId = getParaToLong("id");
		if (typeId == null) {
			renderFailure(500, "id is null");
			return;
		}
		TgType type = TgType.dao.findById(typeId);
		if (type == null) {
			renderFailure(404, "type not found");
			return;
		}
		boolean flag = type.delete();
		if (flag) {
			renderSuccess();
		} else {
			renderFailure();
		}
	}
}
